<template>
  <div class="dashboard-container">
    <div class="app-container">
      <headerTool>
        <div slot="after">
          <el-button type="success" size="small" @click="exportClick">
            导出
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="
              $router.push({ path: '/import', query: { type: 'employee' } })
            "
            >导入</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </div>
      </headerTool>

      <el-card>
        <el-table border :data="empData">
          <el-table-column
            type="index"
            label="序号"
            width="120px"
            style="text-align:center"
          ></el-table-column>
          <el-table-column
            sortable
            width="120px"
            prop="username"
            label="姓名"
          ></el-table-column>
          <el-table-column
            sortable
            width="120px"
            prop="staffPhoto"
            label="头像"
            style="text-align:center"
          >
            <template slot-scope="{ row }">
              <img
                :src="row.staffPhoto"
                v-imgerror="defaultPhoto"
                v-imgunload="unloadPhoto"
                alt=""
                style="width:80px"
                @click="imgClick(row.staffPhoto)"
              /> </template
          ></el-table-column>
          <el-table-column
            sortable
            width="200px"
            prop="mobile"
            label="手机号"
          ></el-table-column>
          <el-table-column
            sortable
            width="120px"
            prop="workNumber"
            label="工号"
          ></el-table-column>
          <el-table-column
            sortable
            width="120px"
            prop="formOfEmployment"
            label="聘用形式"
          >
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | sortEmp }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            width="120px"
            prop="departmentName"
            label="部门"
          ></el-table-column>
          <el-table-column
            sortable
            width="200px"
            prop="timeOfEntry"
            label="入职时间"
          >
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            sortable
            width="120px"
            prop="enableState"
            label="是否在职"
          >
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            width="200px"
            prop="correctionTime"
            label="转正时间"
          >
            <template slot-scope="{ row }">
              {{ row.correctionTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="240px" label="操作">
            <template slot-scope="{ row }">
              <el-link
                type="primary"
                @click="
                  $router.push(
                    `/employees/detail/${row.id}?formOfEmployment=${row.formOfEmployment}`
                  )
                "
                >查看</el-link
              >
              <el-link type="primary">转正</el-link>
              <el-link type="primary">调岗</el-link>
              <el-link type="primary">离职</el-link>
              <el-link type="primary" @click="roleClick(row.id)">角色</el-link>
              <el-link type="primary" @click="delEmp(row.id)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <!-- 页码 -->
        <el-pagination
          style="text-align:center;margin-top:20px"
          :current-page="pageInfo.page"
          :page-size="pageInfo.size"
          :total="pageInfo.total"
          @current-change="pageChange"
          layout="total,prev,pager,next"
        ></el-pagination>
      </el-card>

      <addEmployee :showDialog.sync="showDialog" />

      <!-- 显示二维码 -->
      <el-dialog :visible="showqr" title="二维码" @close="showqr = false">
        <el-row type="flex" justify="center">
          <canvas ref="canvas"></canvas>
        </el-row>
      </el-dialog>

      <!-- 角色弹窗 -->
      <rolePer
        ref="roleper"
        :showRoleDialog.sync="showRoleDialog"
        :id="currentId"
      ></rolePer>
    </div>
  </div>
</template>

<script>
import { getEmpList, delEmp } from "@/api/employees";

// 导入组件
import addEmployee from "./components/add-employee.vue";

import rolePer from "./components/role-per.vue";

// 导入枚举类型
import employeeType from "@/api/constant/employees";

// 导入过滤器
import { formatDate } from "@/filters";

import QRCode from "qrcode";

export default {
  name: "employee",
  components: {
    addEmployee,
    rolePer
  },
  data() {
    return {
      // 控制角色弹窗
      showRoleDialog: false,
      currentId: "",
      showqr: false,
      // 新增员工弹窗
      showDialog: false,
      defaultPhoto: require("@/assets/common/head.jpg"),
      unloadPhoto: require("@/assets/common/zw.webp"),
      empData: [],
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      }
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    // 角色的点击事件
    roleClick(id) {
      this.currentId = id;
      this.showRoleDialog = true;
      this.$refs.roleper.getEmpInfo(id);
      this.$refs.roleper.getRoleList();
    },

    imgClick(url) {
      if (url) {
        this.showqr = true;
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.canvas, url, function(error) {});
        });
      } else {
        this.$message.warning("该用户没有头像哦！！");
      }
    },

    async getEmployeeList() {
      let res = await getEmpList(this.pageInfo);
      this.empData = res.data.rows;
      this.empData.forEach(item => {
        item.enableState = item.enableState == 1 ? true : false;
      });
      this.pageInfo.total = res.data.total;
    },
    pageChange(val) {
      this.pageInfo.page = val;
      this.getEmployeeList();
    },
    async delEmp(id) {
      try {
        await this.$confirm("确定要删除吗？");
        await delEmp(id);
        if (this.empData.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--;
        }
        this.getEmployeeList();
      } catch (error) {
        console.log(error);
      }
    },

    // 导出
    async exportClick() {
      // 发送请求获取所有员工的数据
      let res = await getEmpList({ page: 1, size: this.pageInfo.total });
      let list = res.data.rows;

      let changeKey = {
        姓名: "username",
        手机号: "mobile",
        工号: "workNumber",
        部门: "departmentName",
        入职时间: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正时间: "correctionTime"
      };

      let header = Object.keys(changeKey);

      let results = list.map(item => {
        let arr = header.map(v => {
          if (v == "入职时间" || v == "转正时间") {
            return formatDate(item[changeKey[v]]);
          }
          return item[changeKey[v]];
        });
        return arr;
      });

      import("@/vendor/Export2Excel").then(excel => {
        excel.export_json_to_excel({
          header: header, //表头 必填
          data: results //具体数据 必填
          // filename: 'excel-list', //非必填
          // autoWidth: true, //非必填
          // bookType: 'xlsx' //非必填
        });
      });
    }
  },
  filters: {
    sortEmp(val) {
      let list = employeeType.hireType.filter(item => item.id == val);
      return list[0] ? list[0].value : "未知";
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog__header {
    background-color: #287fc9;
  }
  .has-gutter th {
    text-align: center;
  }
  .el-table {
    .el-table_1_column_11 {
      .cell {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }

    .el-table__row {
      td {
        text-align: center;
      }
    }
  }
}
</style>
